package com.letoy.study.config.auth;

import com.letoy.study.entity.EmailPasswordAuthenticationToken;
import com.letoy.study.service.MyAuthUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

public class MyAuthenticationProvider implements AuthenticationProvider {

    MyAuthUserService myAuthUserService;


    public MyAuthenticationProvider(MyAuthUserService myAuthUserService){
        this.myAuthUserService = myAuthUserService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println("My Provider");
        EmailPasswordAuthenticationToken token = (EmailPasswordAuthenticationToken) authentication;
        UserDetails user = myAuthUserService.getUserByEmailPassword((String)token.getPrincipal(),(String)token.getCredentials());
        System.out.println(user.toString());
        if(user == null){
            return null;
        }else {
            UsernamePasswordAuthenticationToken result =
                    new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
            result.setDetails(token.getDetails());
            System.out.println("登录成功");
            return result;
        }
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return EmailPasswordAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
